﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Emporium_Web.Controls;
using System.Web.UI.WebControls;
using Emporium_Web.DBML;

namespace Emporium_Web
{
    public partial class TallaAdd : System.Web.UI.UserControl
    {
        public event EventHandler agregarClick;

        public string SortExpression
        {
            get
            {
                return ViewState["gv_SortExpression"] == null ? "" : ViewState["gv_SortExpression"].ToString();
            }
            set
            {
                ViewState["gv_SortExpression"] = value;
            }
        }

        public string SortDirection
        {
            get
            {
                return ViewState["gv_SortDirection"] == null ? "" : ViewState["gv_SortDirection"].ToString();
            }
            set
            {
                ViewState["gv_SortDirection"] = value;
            }
        }

        public int CodigoSeleccionado
        {
            get
            {
                return ViewState["CodigoSeleccionado"] == null ? 0 : Convert.ToInt32(ViewState["CodigoSeleccionado"]);
            }
            set
            {
                ViewState["CodigoSeleccionado"] = value;
            }
        }

        public string DescripcionSeleccionado
        {
            get
            {
                return ViewState["DescripcionSeleccionado"] == null ? "" : ViewState["DescripcionSeleccionado"].ToString();
            }
            set
            {
                ViewState["DescripcionSeleccionado"] = value;                
            }
        }

        /// <summary>
        /// Es el código de grupo
        /// </summary>
        public int GrupoId
        {
            get { return ViewState["GrupoId"] == null ? -1 : (int)ViewState["GrupoId"]; }
            set { ViewState["GrupoId"] = value; }
        }
      


        protected void Page_Load(object sender, EventArgs e)
        {
            warningMessage.Visible = false;
            errorMessage.Visible = false;
        }

        protected void btnAceptar_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < gvTallas.Rows.Count; i++)
            {
                if ((int)gvTallas.DataKeys[i][0] == Convert.ToInt32(hdnSeleccion.Value))
                {
                    CodigoSeleccionado = Convert.ToInt32(hdnSeleccion.Value);
                    DescripcionSeleccionado = gvTallas.DataKeys[i][1].ToString();
                    agregarClick(sender,e);
                    return;
                }
            }
        }

        protected void btnBuscar_Click(object sender, EventArgs e)
        {
            try
            {
                ListarTallas();
            }
            catch (Exception x)
            {
                lblErrorMessage.Text = x.Message;
                errorMessage.Visible = true;
            }
        }



        protected void gvPagerPageChanged(object sender, DataNavigatorEventArgs e)
        {
            try
            {
                ListarTallas();
            }
            catch (Exception x)
            {
                lblErrorMessage.Text = x.Message;
                errorMessage.Visible = true;
            }
        }

        protected void gvTallas_Sorting(object sender, GridViewSortEventArgs e)
        {
            try
            {
                if (this.SortExpression != null && this.SortExpression.Equals(e.SortExpression))
                {
                    this.SortDirection = this.SortDirection.ToUpper().Equals("ASC") ? "DES" : "ASC";
                }
                else
                {
                    this.SortDirection = e.SortDirection.ToString().Substring(0, 3);
                }

                this.SortExpression = e.SortExpression;

                ListarTallas();
            }
            catch (Exception x)
            {
                lblErrorMessage.Text = x.Message;
                errorMessage.Visible = true;
            }
        }

        protected void gvTallas_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            try
            {
                if (gvTallas.HeaderRow == null)
                {
                    return;
                }

                this.SortExpression = e.CommandArgument != null ? e.CommandArgument.ToString() : "Id";
                this.SortDirection = e.CommandName.Equals("SortUp") ? "ASC" : "DES";

                ListarTallas();

            }
            catch (Exception x)
            {
                lblErrorMessage.Text = x.Message;
                errorMessage.Visible = true;
            }
        }

        private void ActivaIconoOrdenamiento()
        {
            if (gvTallas.HeaderRow == null)
            {
                return;
            }

            if (this.SortDirection != null && this.SortDirection.ToUpper().Equals("ASC"))
            {
                LinkButton lnkSender = (LinkButton)gvTallas.HeaderRow.FindControl("lnkSortUp" + this.SortExpression);
                LinkButton lnkSortDown = (LinkButton)gvTallas.HeaderRow.FindControl(lnkSender.ID.Replace("SortUp", "SortDown"));
                lnkSortDown.CssClass = "sort-down";
                lnkSender.CssClass = "sort-up active";
            }
            else
            {
                LinkButton lnkSender = (LinkButton)gvTallas.HeaderRow.FindControl("lnkSortDown" + this.SortExpression);
                LinkButton lnkSortUp = (LinkButton)gvTallas.HeaderRow.FindControl(lnkSender.ID.Replace("SortDown", "SortUp"));
                lnkSortUp.CssClass = "sort-up";
                lnkSender.CssClass = "sort-down active";
            }
        }

        public void ListarTallas()
        {
            TablasDataContext database = new TablasDataContext();

            var listarQuery = from tallas in database.TG_Talla
                              join gruposTallas in database.TG_GrupoTallaTalla on tallas.Talla_Id equals gruposTallas.Talla_Id 
                              where ((txtDescripcion.Text.Trim() == "" || tallas.Talla_DescripcionLarga.Contains(txtDescripcion.Text.Trim()))
                              && gruposTallas.GruTal_Id == this.GrupoId)
                              select tallas;

            listarQuery = OrdenarQuery(listarQuery);

            gvTallas.DataSource = listarQuery.Skip((gvPager.CurrentPage - 1) * gvPager.PageSize).Take(gvPager.PageSize).ToList();
            gvTallas.DataBind();

            int totalReg = listarQuery.Count();

            if (totalReg > 0)
            {
                gvTallas.UseAccessibleHeader = false;
                gvTallas.HeaderRow.TableSection = TableRowSection.TableHeader;
                gvPager.Visible = true;
                gvPager.TotalRowCount = totalReg;
                warningMessage.Visible = false;
            }
            else
            {
                lblWarningMessage.Text = Resources.MensajesValidacion.NoDataFound;
                warningMessage.Visible = true;
                gvPager.Visible = false;
            }

            lblMensajeGridFooter.Text = String.Format(Resources.MensajesValidacion.GridFooterMessage, totalReg);
            ActivaIconoOrdenamiento();

            mpeBusquedaCombinacion.Show();
        }

        private IQueryable<TG_Talla> OrdenarQuery(IQueryable<TG_Talla> listarQuery)
        {
            if (this.SortExpression == null || this.SortExpression.Trim().Equals(""))
            {
                this.SortExpression = "Id";
            }

            if (this.SortDirection == null || this.SortDirection.Trim().Equals(""))
            {
                this.SortDirection = "DES";
            }

            if (this.SortExpression == "Id")
            {
                if (this.SortDirection.ToUpper().Equals("ASC"))
                {
                    listarQuery = listarQuery.OrderBy(c => c.Talla_Id);
                }
                else
                {
                    listarQuery = listarQuery.OrderByDescending(c => c.Talla_Id);
                }
            }
            else if (this.SortExpression == "Talla")
            {
                if (this.SortDirection.ToUpper().Equals("ASC"))
                {
                    listarQuery = listarQuery.OrderBy(c => c.Talla_DescripcionCorta);
                }
                else
                {
                    listarQuery = listarQuery.OrderByDescending(c => c.Talla_DescripcionCorta);
                }
            }
            else if (this.SortExpression == "Descripcion")
            {
                if (this.SortDirection.ToUpper().Equals("ASC"))
                {
                    listarQuery = listarQuery.OrderBy(c => c.Talla_DescripcionLarga);
                }
                else
                {
                    listarQuery = listarQuery.OrderByDescending(c => c.Talla_DescripcionLarga);
                }
            }

            return listarQuery;
        }


        protected void btnMostrarModal_Click(object sender, EventArgs e)
        {
            ListarTallas();
        }
    }
}